﻿using System;
using System.Collections.Generic;
using System.IO;

namespace ET.Score.SharedLibrary.LogCleanner
{
    /// <summary>
    /// 过期程序日志清理器
    /// </summary>
    public abstract class LogCleaner : ILogCleaner
    {
        private readonly IEnumerable<string> logFolders;

        /// <summary>
        /// 
        /// </summary>
        /// <param name="logFolders">包含日志文件的文件夹路径</param>
        protected LogCleaner(IEnumerable<string> logFolders)
        {
            if (logFolders == null)
                throw new ArgumentNullException("logFolders");
            this.logFolders = logFolders;
        }

        public void Cleanup()
        {
            foreach (var folder in logFolders)
            {
                if (Directory.Exists(folder))
                    CleanupFolder(folder);
            }
        }

        // 对一个日志文件夹进行清理
        private void CleanupFolder(string folderPath)
        {
            /* 对文件夹和文件可执行不同的策略 */
            foreach (var subFolder in Directory.GetDirectories(folderPath))
            {
                if (CanDeleteFolder(subFolder))
                {
                    try
                    {
                        Directory.Delete(subFolder,true);
                    }
                    catch (UnauthorizedAccessException)
                    {
                    }
                    catch (IOException)
                    {
                    }
                }
            }

            foreach (var file in Directory.GetFiles(folderPath))
            {
                if (CanDeleteFile(file))
                {
                    try
                    {
                        File.Delete(file);
                    }
                    catch (UnauthorizedAccessException)
                    {
                    }
                    catch (IOException)
                    {
                    }
                }
            }

        }

        /// <summary>
        /// 验证目录下的文件是否可删除，即符合日志删除的策略。
        /// </summary>
        /// <param name="filePath"></param>
        /// <returns></returns>
        protected abstract bool CanDeleteFile(string filePath);

        /// <summary>
        /// 验证目录下的子目录是否可删除，即符合日志删除的策略。
        /// </summary>
        /// <param name="folderPath"></param>
        /// <returns></returns>
        protected abstract bool CanDeleteFolder(string folderPath);
    }
}